//
//  GGColoursTextView.m
//  GGLabelLimitDemo
//
//  Created by 顾宜林 on 2020/1/7.
//  Copyright © 2020 顾宜林. All rights reserved.
//

#import "GGColoursTextView.h"

@interface GGColoursTextView ()
@property (nonatomic,strong) CAGradientLayer *gradientLayer;
@end

@implementation GGColoursTextView

- (instancetype)initWithFrame:(CGRect)frame
                         font:(CGFloat)font{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.textLabel];
        self.textLabel.font = [UIFont systemFontOfSize:font];
    }
    return self;
}

- (void)setColours{
        // 创建渐变层
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        self.gradientLayer = gradientLayer;
        gradientLayer.frame = self.textLabel.bounds;
        [gradientLayer setStartPoint:CGPointMake(0, 0)];
        [gradientLayer setEndPoint:CGPointMake(1, 0)];
        gradientLayer.colors = @[(id)[self randomColor].CGColor, (id)[self randomColor].CGColor,(id)[self randomColor].CGColor];
        [self.layer addSublayer:gradientLayer];
        // mask层工作原理:按照透明度裁剪，只保留非透明部分，文字就是非透明的.
        // 因此：label不能设置非透明的背景颜色，否则无法剪裁；字体颜色不能是透明的
        gradientLayer.mask = self.textLabel.layer;
        
        // 利用定时器，快速的切换渐变颜色
        CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(textColorChange)];
        [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.textLabel.frame = self.bounds;
    [self setColours];
}

- (void)setText:(NSString *)text{
    _text = text;
    self.textLabel.text = text;
}

// 随机颜色方法
-(UIColor *)randomColor{
    CGFloat r = arc4random_uniform(256) / 255.0;
    CGFloat g = arc4random_uniform(256) / 255.0;
    CGFloat b = arc4random_uniform(256) / 255.0;
    return [UIColor colorWithRed:r green:g blue:b alpha:1];
}

// 定时器触发方法
-(void)textColorChange {
    _gradientLayer.colors = @[(id)[self randomColor].CGColor,
                              (id)[self randomColor].CGColor,
                              (id)[self randomColor].CGColor,
                              (id)[self randomColor].CGColor,
                              (id)[self randomColor].CGColor];
}

- (UILabel *)textLabel{
    if (_textLabel == nil) {
        _textLabel = [[UILabel alloc]init];
        _textLabel.numberOfLines = 0;
    }
    return _textLabel;
}
@end
